using Microsoft.Data.SqlClient;
using ReportToolAPI.Models;

namespace ReportToolAPI.Services
{
    /// <summary>
    /// 数据库连接测试服务
    /// </summary>
    public class DatabaseTestService
    {
        /// <summary>
        /// 测试数据库连接
        /// </summary>
        public static async Task<(bool success, string message)> TestConnectionAsync(TestConnectionRequest request)
        {
            try
            {
                var connectionString = BuildConnectionString(
                    request.Ip,
                    request.Port,
                    request.DatabaseName,
                    request.Username,
                    request.Password
                );

                using var connection = new SqlConnection(connectionString);
                await connection.OpenAsync();
                
                // 执行简单查询验证连接
                using var command = new SqlCommand("SELECT 1", connection);
                await command.ExecuteScalarAsync();

                return (true, "数据库连接成功");
            }
            catch (SqlException ex)
            {
                return (false, $"数据库连接失败: {ex.Message}");
            }
            catch (Exception ex)
            {
                return (false, $"连接测试异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 从配置构建连接字符串
        /// </summary>
        public static string BuildConnectionString(DatabaseConfig config)
        {
            return BuildConnectionString(
                config.Ip,
                config.Port,
                config.DatabaseName,
                config.Username,
                config.Password
            );
        }

        /// <summary>
        /// 构建 SQL Server 连接字符串
        /// </summary>
        private static string BuildConnectionString(string ip, int port, string databaseName, string username, string password)
        {
            return $"Server={ip},{port};Database={databaseName};User Id={username};Password={password};TrustServerCertificate=True;Connect Timeout=5;";
        }
    }
}




